package com.future.common.base;

import java.util.HashMap;
import java.util.Map;

import com.future.common.bean.Result;
import com.future.common.exception.BadRequestException;
import com.future.common.global.PlatFormContext;
import com.future.common.jfinalcustom.MyQrCodeRender;
import com.future.common.utils.ValidationUtil;
import com.future.model.SysUser;
import com.jfinal.core.Controller;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Table;
import com.jfinal.plugin.activerecord.TableMapping;

import cn.hutool.core.bean.BeanUtil;

/**
 * controller的基类，封装一些通用的逻辑
 * 
 * @author Leon.Zhang
 *
 */
public class BaseController extends Controller {
	private Map<String, Object> result = new HashMap<String, Object>();

	protected void addResult(String key, Object value) {
		this.result.put(key, value);
	}

	/**
	 * 直接返回结果
	 * 
	 * @param result
	 */
	protected void renderResult(Object result) {
		Result res = new Result();
		res.set_success(true);
		res.set_message("");
		res.setResult(result);
		res.setCode("200");
		renderJson(res);
	}

	/**
	 * 返回多值的命名结果
	 * 
	 * @param key
	 * @param result
	 */
	protected void renderResult() {
		if (this.result.size() == 0) {
			throw new RuntimeException("调用renderResult()之前需要先调用addResult");
		}
		Result res = new Result();
		res.set_success(true);
		res.set_message("");
		res.setResult(this.result);
		res.setCode("200");
		renderJson(res);
	}

	protected void renderResult(String key, Object result) {
		Result res = new Result();
		res.set_success(true);
		res.set_message("");
		res.setResult(Kv.by(key, result));
		res.setCode("200");
		renderJson(res);
	}

	/**
	 * 执行成功
	 */
	protected void renderSuccess() {
		Result res = new Result();
		res.set_success(true);
		res.set_message("");
		res.setResult(null);
		res.setCode("200");
		renderJson(res);
	}

	/**
	 * 从request中获取json,校验hibernate validator 注解
	 * 
	 * @param type
	 * @return
	 */
	protected <T> T getJsonBody(Class<T> type) {
		return getJsonBody(type, true);
	}

	/**
	 * 从json中获取bean并转为相应的model
	 * 
	 * @param type
	 * @return
	 */
	protected <T, M extends Model<M>> M getJsonBodyToModel(Class<T> beanType, Class<M> modelType) {
		T t = getJsonBody(beanType, true);
		return beanToModel(t, modelType);
	}

	/**
	 * 获取jsonbody
	 * 
	 * @param type
	 * @param validate
	 * @return
	 */
	protected <T> T getJsonBody(Class<T> type, boolean validate) {
		String jsonStr = HttpKit.readData(getRequest());
		T result = null;
		try {
			result = JsonKit.parse(jsonStr, type);
		} catch (Exception e) {
			throw new BadRequestException("Bad Request");
		}
		if (result != null && validate) {
			ValidationUtil.checkValidation(result);
		}
		return result;
	}

	/**
	 * 支持qrcode底部带文字
	 * 
	 * @param content
	 * @param width
	 * @param height
	 * @param errorCorrectionLevel
	 * @param underWords
	 */
	public void renderQrCode(String content, int width, int height, char errorCorrectionLevel, String upperWords,
			String underWords) {
		render(new MyQrCodeRender(content, width, height, errorCorrectionLevel, upperWords, underWords));
	}

	/**
	 * 获取当前用户的id
	 * 
	 * @return
	 */
	public Long getCurrentUserId() {
		return PlatFormContext.getCurrentUser().getUserid();
	}

	/**
	 * 获取当前用户的id
	 * 
	 * @return
	 */
	public String getCurrentUserName() {
		return PlatFormContext.getCurrentUser().getName();
	}

	/**
	 * 获取当前用户
	 * 
	 * @return
	 */
	public SysUser getCurrentUser() {
		return PlatFormContext.getCurrentUser();
	}

	/**
	 * Bean to ModelClass
	 * 
	 * @param Bean
	 * @param modelClass
	 * @return
	 */
	public <T extends Model<T>> T beanToModel(Object Bean, Class<T> modelClass) {
		T t;
		Table table = TableMapping.me().getTable(_getUsefulClass(modelClass));
		try {
			t = modelClass.newInstance();
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		Map<String, Object> beanMap = BeanUtil.beanToMap(Bean);
		/**
		 * 只有当表中存在该字段的时候才会放进去，防止造成混乱
		 */
		if (beanMap != null) {
			beanMap.forEach((key, value) -> {
				if (table.getColumnNameSet().contains(key)) {
					t.set(key, value);
				}
			});
		}
		return t;
	}

	private Class<? extends Model> _getUsefulClass(Class c) {
		return c.getName().indexOf("$$EnhancerBy") == -1 ? c : c.getSuperclass();
	}

	protected String getFirstImg(String content) {
		if (StrKit.isBlank(content)) {
			return "";
		} else {
			int beginImg = content.indexOf("<img src");
			if (beginImg < 0) {
				return "";
			} else {
				beginImg = beginImg + 10;
				int lastImg = content.indexOf("\"", beginImg);
				return content.substring(beginImg, lastImg);
			}
		}
	}
}
